package com.demo.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ThreadManager {
    private static final ThreadManager instance = new ThreadManager();
    private final List<Thread> list = new ArrayList<>();

    public void submit(Thread... threads) {
        for (Thread thread : threads) {
            thread.start();
            list.add(thread);
        }
    }

    private ThreadManager() {
    }

    /**
     * 异步等待所有提交的线程执行完毕，然后执行回调方法。
     *
     * @param callback 回调方法
     */
    public void waitFor(CallBackFunction callback) {
        new Thread(() -> {
            try {
                waitFor();
                callback.doCallBack();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    public void waitFor() throws InterruptedException {
        ListIterator<Thread> threadListIterator = list.listIterator();
        while (threadListIterator.hasNext()) {
            Thread thread = threadListIterator.next();
            thread.join();
            threadListIterator.remove();
        }
    }

    public static ThreadManager getInstance() {
        return instance;
    }

    /**
     * 简单的回调函数
     */
    public interface CallBackFunction {

        void doCallBack();

    }

}
